package com.controller.user;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.dto.GooglemapsDTO;
import com.dto.merchant.OrderDTO;
import com.dto.merchant.UserDTO;
import com.model.dao.GooglemapsTable;
import com.model.dao.GooglemapsTableDAO;
import com.model.dao.OrderTable;
import com.model.dao.UserTable;
import com.model.dao.UserTableDAO;

@ManagedBean(name = "myAccountController")
@SessionScoped
public class MyAccountController implements Serializable {

	private static final long serialVersionUID = -2834751471773104065L;

	public boolean updateDetails(UserDTO dto) throws Exception {
		UserTableDAO dao = new UserTableDAO();
		dao.updateUser(dto);
		return true;
	}

	public boolean updateGooglemap(UserDTO dto, boolean add) throws Exception {
		GooglemapsTableDAO dao = new GooglemapsTableDAO();
		GooglemapsTable table = new GooglemapsTable();
		table.setIdgooglemapsTable(dto.getIduserTable());
		table.setLang(dto.getGooglemapsDTO().getLang());
		table.setLat(dto.getGooglemapsDTO().getLat());
		UserTableDAO dao2 = new UserTableDAO();
		UserTable usertable = dao2.findById(dto.getIduserTable());
		table.setUserTable(usertable);
		if (add)
			dao.persist(table);
		else
			dao.merge(table);
		return true;
	}

	public List<GooglemapsDTO> findAll() throws Exception {
		GooglemapsTableDAO dao = new GooglemapsTableDAO();
		List<GooglemapsDTO> mapList = new ArrayList<GooglemapsDTO>();
		List<GooglemapsTable> list = dao.findByAll();
		for (GooglemapsTable table : list) {
			GooglemapsDTO dto = new GooglemapsDTO();
			dto.setId(table.getIdgooglemapsTable());
			dto.setLang(table.getLang());
			dto.setLat(table.getLat());
			UserDTO userDTO = new UserDTO();
			userDTO.setArea(table.getUserTable().getArea());
			userDTO.setCity(table.getUserTable().getCity());
			userDTO.setEmail(table.getUserTable().getEmail());
			userDTO.setHouseno(table.getUserTable().getHouseno());
			userDTO.setLandmark(table.getUserTable().getLandmark());
			userDTO.setMobileno(table.getUserTable().getMobileno());
			userDTO.setName(table.getUserTable().getName());
			userDTO.setStreet(table.getUserTable().getStreet());
			userDTO.setIduserTable(table.getUserTable().getIduserTable());
			List<OrderDTO> orderList = new ArrayList<OrderDTO>();
			for(OrderTable orderTable:table.getUserTable().getOrderTables()){
				OrderDTO dto2 = new OrderDTO();
				dto2.setOid(orderTable.getOrderId() + "");
				dto2.setOrderDate(orderTable.getDateOfOrder());
				dto2.setStatus(orderTable.getOrderStatus());
				dto2.setDeliveryDate(orderTable.getDateOfDelivery());
				dto2.setAmount(orderTable.getPrice());
				orderList.add(dto2);
			}
			userDTO.setOrderTables(orderList);
			dto.setUserDTO(userDTO);
			mapList.add(dto);
		}
		return mapList;
	}
}
